package org.vaadin.nf4v.core.navigation.event;

import org.vaadin.nf4v.core.navigation.NavigationRequest;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;

/**
 * Utility class to support navigation request state change events broadcast.
 * Used internally by framework.
 */
public class EventSupport implements Serializable {
    private Map<NavigationState, List<NavigationListener>> listeners = new EnumMap<NavigationState, List<NavigationListener>>(NavigationState.class);

    public void addNavigationListener(NavigationListener listener, NavigationState... states) {
        if (listener == null) {
            throw new IllegalArgumentException("Listener class can't be null");
        }
        for (NavigationState state : states.length > 0 ? states : NavigationState.values()) {
            addListener(listener, state);
        }
    }

    public void removeNavigationListener(NavigationListener listener, NavigationState... states) {
        if (listener == null) {
            throw new IllegalArgumentException("Listener class can't be null");
        }
        for (NavigationState state : states.length > 0 ? states : NavigationState.values()) {
            removeListener(listener, state);
        }
    }

    public void fireEvent(NavigationRequest request) {
        List<NavigationListener> list = listeners.get(request.getState());
        if (list != null) {
            for (NavigationListener listener : list) {
                if (request.isCancelled()) return;
                listener.onNavigation(request);
            }
        }
    }

    private void addListener(NavigationListener listener, NavigationState state) {
        List<NavigationListener> list = listeners.get(state);
        if (list == null) {
            list = new ArrayList<NavigationListener>();
            listeners.put(state, list);
        }
        list.add(listener);
    }

    private void removeListener(NavigationListener listener, NavigationState state) {
        List<NavigationListener> list = listeners.get(state);
        if (list != null) {
            list.remove(listener);
        }
    }
}
